package com.yicheng.statistics.repo.cassandra



import java.util.Date

import scala.collection.JavaConversions.iterableAsScalaIterable
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

import com.datastax.driver.core.Row
import com.datastax.driver.core.Statement
import com.datastax.driver.core.querybuilder.{ QueryBuilder => qb }
import com.datastax.driver.core.utils.UUIDs
import com.carcloud.gateway.bean.alarm.AlarmInfo.AlarmDetail.AlarmVehicle
import com.carcloud.gateway.bean.alarm
import com.carcloud.gateway.bean.alarm.AlarmInfo.AlarmDetail

object AlarmInfoDb {
  lazy val table = "t_alarm_info"

  import CassandraDB._
  import CassandraHelper._
  
  def fromRow(row: Row) = {
    com.yicheng.statistics.repo.model.Data.AlarmInfo(
      row.getInt("device_type"),
      row.getString("device_id"),
      new Date(UUIDs.unixTimestamp(row.getUUID("alarm_time"))),
      Option(row.getString("sub_device")),
      Option(row.getInt("alarm_type")),
      Option(row.getInt("alarm_code")),
      Option(row.getInt("alarm_source")),
      Option(row.getInt("alarm_level")),
      Option(row.getTimestamp("alarm_start")),
      Option(row.getTimestamp("alarm_stop")),
      Option(row.getInt("alarm_cnt")),
      Option(row.getString("alarm_text")),
      Option(AlarmDetail.AlarmVehicle(alarm.AlarmVehicle.parseFrom(row.getBytes("alarm_detail").array())))
    )
  }
  
  def list(deviceType: Int, deviceId: String, start: Date, end: Date): Future[Seq[com.yicheng.statistics.repo.model.Data.AlarmInfo]] = {
    val query: Statement = qb.select()
      .from(keyspace, table)
      .where(qb.eq("device_id", deviceId))
      .and(qb.eq("device_type", deviceType))
      .and(qb.gte("alarm_time", UUIDs.startOf(start.getTime())))
      .and(qb.lt("alarm_time", UUIDs.startOf(end.getTime())))
      .orderBy(qb.desc("alarm_time"))
    executeAsync(query).asScala.map(_.map(fromRow).toSeq)
  }
}